<!DOCTYPE html>


<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- this line optimises screen for smart phones-->
<meta name="HandheldFriendly" content="true"/> <!-- this line optimises screen for feature phones-->

<?php
include('script.js');
?>

<title>HandiVote</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link href="js/google-code-prettify/prettify.css" rel="stylesheet">
<link href="bootstrap.min.css" rel="stylesheet">
<link href="bootstrap-responsive.min.css" rel="stylesheet">
<style type="text/css">     
  


body
{
  background-color: Snow;
  margin-top:10px;
  margin-left:10px;
}

fieldset
{
border:1px solid white;
margin-top: 5px;
margin-bottom: 5px;
font-size: 120%;
background-color: Beige;
padding: 10px;
}

div
{
margin-top: 5px;
margin-bottom: 5px;
}

</style>
</head>


<body>
<?php

$mybarcode = 28057448224012;
$mypin     = 4869;


//$question_ids    = array();
//$question_option = array();
// Connect to the database
$con             = mysql_connect("127.0.0.1", "root", "");


if (!$con) {
    die('Could not connect: ' . mysql_error());
}

if (!isset($_POST['barcode'])) {
    
   // $optionNumber = array();
    mysql_select_db("handivote", $con);
    $sql_referendum    = "SELECT * FROM referendum";
    $result_referendum = mysql_query($sql_referendum, $con);
    
    while ($row = mysql_fetch_assoc($result_referendum)) {
        print "<h3>" . $row['title'] . "</h3>"; // prints the name of the referendum
        $startdate = $row['startDate'];
        $enddate   = $row['endDate'];
        
        $id = $row['id'];
        
        $diffStartDate = strtotime("now") - strtotime($startdate); // checks whether the referendum is live
        $diffEndDate   = strtotime("now") - strtotime($enddate); // by comparing start and end date to current time 
        
        if ($diffStartDate > 0 && $diffEndDate < 0) {
            
            $sql_question    = "SELECT * FROM question WHERE refID=" . $id;
            $result_question = mysql_query($sql_question, $con);
            $question_number = 1;

            // take each question for this referendum from the table "question" and print it out
            while ($row2 = mysql_fetch_assoc($result_question)) {             
                $idQ = $row2['id'];
                print "<fieldset><div id = 'q" . strval($idQ) . "' onclick=\"expandElement('paragraph" . strval($idQ) . "');\"><b>Question " . $question_number . ". </b>" . $row2['question'] . " </div>"; //<b id='output".$question_number."'></b>
                print "<div id='paragraph" . strval($idQ) . "' style='display: none;'>";
                //$question_ids[$question_number - 1] = $idQ;
               // $question_option[$idQ]              = 2; // here instead of 1, we are going to have the chosen option for this question
                
                $sql_option    = "SELECT * FROM questionoption WHERE qID=" . $idQ;
                $result_option = mysql_query($sql_option, $con);
                
                print "<form>
                 <select id='select" . $idQ . "' name='question" . $idQ . "'>";
                // take each option for this question and print it out
                // options displayed as a drop down menue
                $optionCounter = 1;
                while ($row3 = mysql_fetch_assoc($result_option)) {
                    print "<option value=" . $row3['id'] . "> " . $row3['option'] . "</option>";
                 }
                
                print "</select><input type='button' class= 'btn btn-info' onclick=\"displayInput('select" . $idQ . "', 'output" . $idQ . "'); 
                updateHidden('select" . $idQ . "','hidden_option" . $idQ . "');
                contractElement('paragraph" . strval($idQ) . "');\" name='submit' value='Save'></form></div>";
                
                print "<div id='choice" . strval($idQ) . "' stype='display: none;'><b style = 'color:red' id='output" . $question_number . "'></b></div></fieldset>";
                $question_number = $question_number + 1;
             }
            
            $barcode = "";
            $pin     = "";
            
            // htmlentities protects from hakers exploiting the PHP_SELF feature
            // I am using POST instead of GET because it is more secure - I dont want the barcode and pin to be attached to the url - protects from sholdersurfing
            // also if I use GET the browser will cache the input from the user and I dont want that, because someone can see how they voted from thir browser
            print "<form name='authentication' method= 'post' action='" . htmlentities($_SERVER['PHP_SELF']) . "' class='form-inline'> <label for='barcode'>Barcode:</label> <input type='number' name='barcode' id='barcode' required /> </br><label for='pin'>PIN:</label> <input type='number' name='pin' id='pin' required /></fieldset>";
            
            $sql_question    = "SELECT * FROM question WHERE refID=" . $id;
            $result_question = mysql_query($sql_question, $con);
            
            while ($row3 = mysql_fetch_assoc($result_question)) {
                print "<input type='hidden' value = '' name='hidden_option" . $row3['id'] . "' id='hidden_option" . $row3['id'] . "'/>";

             }
            



            print "</br></br><input type='submit' class='btn btn-success btn-large' name='submit' value = 'Submit Vote' /></form></br>";
         }
     }
 }




else {
    print "<div id='thankyou' style='display: block;'>
    <h3><input type='image' src='tick.jpg' width='60' height='40'>Thank you for voting</h3>
    <h4>Please come back to this page after the referendum is over to see the results and to verify your vote.</h4>
    </div>";

    if (isset($_POST['submit'])) {
        $barcode = $_POST['barcode'];
        $pin     = $_POST['pin'];
     }

    $hidden_option1 = $_POST['hidden_option1'];

    $result_verify = file_get_contents("http://www.dcs.gla.ac.uk/~macneisd/barcode.cfm?barcode=" . $barcode . "&pin=" . $pin);
    
      // this connects to the webservie passing it the barcode and the pin
      // returns 1 if valid combination
      // returns 0 if invalid combination
     
    if ($result_verify == 1) {
       $con = mysql_connect("127.0.0.1", "root", "");
       if (!$con) {
         die('Could not connect: ' . mysql_error());
         }

    mysql_select_db("handivote", $con);

    $sql_referendum    = "SELECT * FROM referendum";
    $result_referendum = mysql_query($sql_referendum, $con);
    while ($row = mysql_fetch_assoc($result_referendum)) {
        
              $startdate = $row['startDate'];
              $enddate   = $row['endDate'];
              $id = $row['id'];
        
              $diffStartDate = strtotime("now") - strtotime($startdate); // checks whether the referendum is live
              $diffEndDate   = strtotime("now") - strtotime($enddate); // by comparing start and end date to current time 
        
              if ($diffStartDate > 0 && $diffEndDate < 0) {
            

                 $findBarcode = "SELECT * FROM vote WHERE barcode=".$barcode ;
                 $resultFindBarcode = mysql_query($findBarcode, $con);
                 if (!mysql_query($findBarcode, $con)) {
                     die('Error: ' . mysql_error());
                     }

                     if (mysql_num_rows($resultFindBarcode)>0) {
                         $optionsFromDB = array();
            
                         while ($row4 = mysql_fetch_assoc($resultFindBarcode)) {
                              $optionsFromDB[] = $row4['optionID'];
                             }
                                    // for each in new options array : 
                                    // compare with old option
                                    // if any of them is different
                                    // set void to 1 for each vote of the barcode

                         $sql_question    = "SELECT * FROM question WHERE refID=" . $id;
                         $result_question = mysql_query($sql_question, $con);
            
                         while ($row7 = mysql_fetch_assoc($result_question)) {
            
                               $idQ = $row7['id'];
                               $hidden_option = $_POST['hidden_option'.$idQ];
                 
                             if (!in_array($hidden_option, $optionsFromDB)) {
                                 $updateVoid = "UPDATE `vote` SET `void`= '1' WHERE `barcode` LIKE '" . $barcode . "'";
                                 mysql_query($updateVoid, $con);
                                 }
                             }
                         }

                     else {
                         $sql_question    = "SELECT * FROM question WHERE refID=" . $id;
                         $result_question = mysql_query($sql_question, $con);
            
                         while ($row2 = mysql_fetch_assoc($result_question)) {
            
                         $idQ = $row2['id'];

                         $hidden_option = $_POST['hidden_option'.$idQ];

                         $insert = "INSERT INTO `handivote`.`vote` (`id`, `barcode`, `pin`, `questionID`, `optionID`) VALUES (NULL, '" . $barcode . "', '" . $pin . "', '" . $idQ . "', '" . $hidden_option. "');";
                
                
                
                         if (!mysql_query($insert, $con)) {
                             die('Error: ' . mysql_error());
                             }
                         }
                      }
             }
         }

       
         
     }
    
 }


mysql_close($con);
?> 
</body>
</html>

